<template>
  <div>
    <!--面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="active - 0"
        finish-status="success"
        process-status="process"
      >
        <el-step title="基本信息"> </el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧标签页 -->
      <el-form
        label-width="80px"
        :model="addGoods"
        :rules="addGoodsRules"
        ref="add_goods_ref"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          @tab-click="handleClick()"
          :before-leave="handleleave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoods.goods_name"> </el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoods.goods_price"> </el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoods.goods_weight"> </el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoods.goods_number"> </el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                :options="categoriesListAll"
                :props="cateProps"
                v-model="selectKeys"
                @change="changeParamsId()"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item, j) in paramsList" :key="j">
              <p>{{ item.attr_name }}</p>
              <el-checkbox-group
                v-model="item.attr_vals"
                @change="handleChangeMany(paramsList)"
              >
                <el-checkbox
                  v-for="(items, i) in item.attr_vals"
                  :key="i"
                  :label="items"
                  :border="true"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="(item, j) in paramsList" :key="j">
              <p>{{ item.attr_name }}</p>
              <el-checkbox-group
                v-model="item.attr_vals"
                @change="handleChangeOnly(paramsList)"
              >
                <el-checkbox
                  v-for="(items, i) in item.attr_vals"
                  :key="i"
                  :label="items"
                  :border="true"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 上传图片 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片要上传的后台Api地址 -->
            <el-upload
              class="upload-demo"
              action="http://rambuild.cn:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="addGoods.goods_introduce"
              class="editor"
            ></quill-editor>
            <!-- 增加商品按钮 -->
            <el-button type="primary" @click="addGood()" class="bton"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览框 -->
    <el-dialog title="图片预览" :visible.sync="dialogPreview" width="50%">
      <el-image :src="previewUrl" alt=""></el-image>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "0",
      addGoods: {
        goods_name: "",
        goods_cat: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      attrsMany: [],
      attrsOnly: [],
      //商品分类列表
      categoriesListAll: [],
      //动态参数列表
      paramsList: [],
      selectKeys: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      paramsInfo: {
        id: 0,
        sel: "many",
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      //图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //图片预览绑定
      dialogPreview: false,
      //图片路径
      previewUrl: "",
    };
  },
  created() {
    this.getAllCategories();
  },
  methods: {
    changeParamsId() {
      this.addGoods.goods_cat = this.selectKeys.join(",");
      this.paramsInfo.id = this.selectKeys[2];
      this.getParamsList();
      // console.log(this.addGoods.goods_cat);
    },
    //获取所有商品分类
    async getAllCategories() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取失败");
      // this.$message.success(res.meta.msg);
      this.categoriesListAll = res.data;
      this.total = res.data.length;
    },
    //获取参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(
        `categories/${this.paramsInfo.id}/attributes`,
        {
          params: this.paramsInfo,
        }
      );
      if (res.meta.status != 200) return this.$message.error("获取失败");
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      this.paramsList = res.data;
      if (this.paramsInfo.sel === "many") {
        this.attrsMany = this.paramsList;
      } else {
        this.attrsOnly = this.paramsList;
      }
      console.log(this.paramsList);
    },
    //处理选择参数
    handleChangeMany(params) {
      this.attrsMany = params;
      console.log(this.attrsMany);
    },
    handleChangeOnly(params) {
      this.attrsOnly = params;
      console.log(this.attrsOnly);
    },
    handleClick() {
      if (this.active === "1") {
        this.paramsInfo.sel = "many";
        this.getParamsList();
        return;
      }
      if (this.active === "2") {
        this.paramsInfo.sel = "only";
        this.getParamsList();
        return;
      }
    },
    //未选择商品分类阻止tabs跳转
    handleleave(activeName, oldActiveName) {
      if (oldActiveName === "0") {
        if (this.paramsInfo.id === 0) {
          this.$message.error("请选择商品类型");
          return false;
        } else {
          return true;
        }
      }
    },
    //移除图片
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      const index = this.addGoods.pics.indexOf(file.response.data.tmp_path);
      this.addGoods.pics.splice(index, 1);
      console.log(this.addGoods.pics);
    },
    //处理图片预览
    handlePreview(file) {
      console.log(file);
      this.previewUrl = file.response.data.url;
      this.dialogPreview = true;
    },
    //处理上传成功
    handleSuccess(response) {
      // console.log(response);
      const res = {
        pic: response.data.tmp_path,
      };
      // console.log(res);
      this.addGoods.pics.push(res);
      // console.log(this.addGoods.pics);
    },
    //发送添加商品请求
    addGood() {
      this.$refs.add_goods_ref.validate(async (valid) => {
        if (!valid) return;
        this.attrsMany.forEach((item) => {
          const itemMany = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addGoods.attrs.push(itemMany);
        });
        this.attrsOnly.forEach((item) => {
          const itemOnly = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addGoods.attrs.push(itemOnly);
        });
        // console.log(this.addGoods);
        const { data: res } = await this.$http.post("goods", this.addGoods);
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("创建商品失败");
        this.$message.success("创建商品成功");
        this.$router.push("/goods");
      });
    },
  },
};
</script>
<style lang='less' scoped>
.el-steps {
  margin: 15px;
  margin-left: 100px;
  width: 60%;
}
.el-input {
  width: 50%;
}
.el-input-number {
  width: 50%;
}
.editor {
  height: 360px;
}
.bton {
  margin-top: 60px;
}
</style>